<template>
  <view>

    <view class="recharge-wrapper">
      <view class="title">充值金额:</view>
      <view class="input u-f-ac">
        <text class="rmb"></text>
        <input v-model="rechargeNumber" type="number" placeholder="请输入充值金额" placeholder-class="placeholder" />
      </view>
    </view>
    <view class="payway-wrapper">
      <!-- <view class="payway-list">
				<view class="wrapper">
					<view>
						<image src="../../../static/wanke/weixin.png" mode=""></image>
					</view>
					<view>微信支付</view>
				</view>
				<radio :checked="checkpay==1" color="#D0B074" @click="changeCheck(1)"></radio>
			</view> -->
      <!--  #ifdef  APP-PLUS -->

      <!--  #endif -->
      <view class="payway-list" v-for="(pay, index) in paymentList" :key="index">
        <view class="wrapper">
          <view>
            <image :src="pay.image" mode="widthFix" style="width: 60rpx;"></image>
          </view>
          <view style="font-weight: 700;">{{ pay.method_name }}</view>
        </view>
        <radio :checked="pay.selected" color="#D0B074" @click="handlePaymentType(pay.plugin_id)"></radio>
      </view>

    </view>
    <view class="recharge_btn u-f-ajc" @click="initiatePay()">
      立即充值
    </view>
    <u-modal v-model="showModal" content="充值成功~"></u-modal>


    <!-- #ifdef H5 -->
    <div class="__pay_form__"></div>
    <!-- #endif -->

  </view>
</template>

<script>
  import * as API_Deposit from '@/api/deposit'
  import * as API_Trade from '@/api/trade.js'
  import * as Payment from '@/common/payment.js'
  import * as API_Openid from '@/api/openid.js'
  import Cache, {
    Keys
  } from '@/utils/cache.js'
  import {
    Foundation,
    RegExp
  } from '@/ui-utils/index.js'
  export default {
    data() {
      return {
        showModal: false,
        // 充值金额
        rechargeNumber: '',
        // 是否是微信浏览器
        isWechatBroswer: false,
        payment_plugin_id: '', //支付方式
        paymentList: [], //支付方式列表
        openid: ''
      }
    },
    mounted() {
      uni.setNavigationBarTitle({
        title: '现金充值'
      })
      this.getPaymentList()
      this.openid = Cache.getItem(Keys.wxopenid)

      // if (options.is_callback == 'yes') {
      //   this.payCallback()
      // }

      // #ifdef APP-PLUS
      this.openid = 'appopenid'
      // #endif

      // // #ifdef H5
      // let code = options.code || ''
      // this.loadH5OpenId(code)
      // // #endif

      // #ifdef MP-WEIXIN
      this.loadMiniOpenId()
      // #endif
    },
    methods: {
      //是否是微信浏览器
      is_weixin() {
        let ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      },
      //明细列表
      handleDetailed() {
        uni.navigateTo({
          url: "/mine-module/balance-detailed"
        })
      },
      //选择支付方式
      handlePaymentType(plugin_id) {
        this.paymentList.forEach(item => {
          item.selected = false
          if (item.plugin_id === plugin_id) {
            item.selected = true
          }
        })
        this.payment_plugin_id = plugin_id
      },

      openMini(response, result) {
        console.log(response, result)
        // #ifdef APP-PLUS
        // 如果是ios 需要先login 然后在 执行下面的代码 isIOS 这个方法根据你项目中的来定义 即可
        if (!this.isAndroid()) {
          uni.login({
            provider: 'weixin',
            success: function(loginRes1) {
              plus.share.getServices(function(res) {
                var sweixin = null;
                for (var i = 0; i < res.length; i++) {
                  var t = res[i];
                  if (t.id == 'weixin') {
                    sweixin = t;
                  }
                }

                if (sweixin) {
                  let path =
                    // `pages/test/test?openid=${that.openid}&num=${that.price}&out_trade_no=${that.ordersn}&goodstitle=${that.title}&type=pay`
                    `pages/test/test?sn=${response.recharge_sn}&type=recharge&token=${uni.getStorageSync('accessToken')}`
                  sweixin.launchMiniProgram({
                    id: 'gh_3e1ea12cfb44',
                    path: path,
                    type: 0, //可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
                  });
                }
              }, function(res) {
                console.log(JSON.stringify(res));
              });
            }
          });
        } else {
          plus.share.getServices(function(res) {
            var sweixin = null;
            for (var i = 0; i < res.length; i++) {
              var t = res[i];
              if (t.id == 'weixin') {
                sweixin = t;
              }
            }
            console.log(sweixin)
            if (sweixin) {
              let path =
                // `pages/test/test?openid=${that.openid}&num=${that.price}&out_trade_no=${that.ordersn}&goodstitle=${that.title}&type=pay`
                `pages/test/test?sn=${response.recharge_sn}&type=recharge&token=${uni.getStorageSync('accessToken')}`
              sweixin.launchMiniProgram({
                id: 'gh_3e1ea12cfb44',
                path: path,
                type: 0, //可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
              });
            }
          }, function(res) {
            console.log(JSON.stringify(res));
          });
        }
        //#endif
      },


      //判断是安卓还是ios
      isAndroid() {
        switch (uni.getSystemInfoSync().platform) {
          case 'android':
            return true;
          case 'ios':
            return false;
          default:
            console.log('运行在开发者工具上')
            break;
        }
      },
      launchMini(item) {
        // #ifdef H5
        // uni.setStorageSync('orderCd', item.orderCd)
        // uni.setStorageSync('sign', item.sign)
        // uni.navigateTo({
        //     url: './testH5'
        // });
        let url = item.qrData
        if (item.browser == "alipay") {
          url = 'alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=' + url
          console.log('广东快付支付宝', url)
        } else if (item.browser == "wxpay") {
          console.log('广东快付微信', url)
        }
        window.location.href = url
        //#endif

        // #ifdef APP-PLUS
        if (item.browser == "alipay") {
          plus.runtime.openURL('alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=' + item
            .qrData)
          console.log('广东快付支付宝')
        } else if (item.browser == "wxpay") {
          uni.setStorageSync('qrData', item.qrData)
          uni.navigateTo({
            url: '/pages/cashier/testH5'
          });
          // plus.runtime.openURL("weixin://dl/business/?ticket="+item.qrData)
        }
        return
        // 如果是ios 需要先login 然后在 执行下面的代码 isIOS 这个方法根据你项目中的来定义 即可
        if (!this.isAndroid()) {
          uni.login({
            provider: 'weixin',
            success: function(loginRes1) {
              plus.share.getServices(function(res) {
                var sweixin = null;
                for (var i = 0; i < res.length; i++) {
                  var t = res[i];
                  if (t.id == 'weixin') {
                    sweixin = t;
                  }
                }

                if (sweixin) {
                  sweixin.launchMiniProgram({
                    id: 'gh_5ef9306a314f',
                    // path: 'pages/index/index?orderCd=26ecbf3363bd4f0b9f9ac39636f179b5&sign=d5606d24a4a5fa20a9d5cc91d2c1b482',
                    path: `pages/index/index?orderCd=${item.orderCd}&sign=${item.sign}`,
                    type: 0
                  });
                }
              }, function(res) {
                console.log(JSON.stringify(res));
              });
            }
          });
        } else {
          plus.share.getServices(function(res) {
            var sweixin = null;
            for (var i = 0; i < res.length; i++) {
              var t = res[i];
              if (t.id == 'weixin') {
                sweixin = t;
              }
            }

            if (sweixin) {
              sweixin.launchMiniProgram({
                id: 'gh_5ef9306a314f',
                path: `pages/index/index?orderCd=${item.orderCd}&sign=${item.sign}`,
                type: 0
              });
            }
          }, function(res) {
            console.log(JSON.stringify(res));
          });
        }
        //#endif
      },

      //支付
      async initiatePay() {
        if (!this.rechargeNumber) {
          this.$u.toast('充值金额不能为空')
          return
        } else if (!RegExp.money.test(this.rechargeNumber)) {
          this.$u.toast('请输入正整数或者两位小数')
          return
        } else if (parseInt(this.rechargeNumber) < 1) {
          this.$u.toast('充值金额最少1元')
          return
        } else if (!this.payment_plugin_id) {
          this.$u.toast('请选择支付方式')
          return
        } else if (this.openid == 'error') {
          this.$u.toast(`openid不正确，不能支付`)
          return
        }

        // #ifdef APP-PLUS
        const client_type = 'NATIVE'
        // #endif

        // #ifdef H5
        const client_type = 'WAP'
        // #endif

        // #ifdef MP-WEIXIN
        const client_type = 'MINI'
        // #endif

        // #ifdef H5
        //非微信内部，跳过获取openid
        if (!this.is_weixin() && this.payment_plugin_id == 'weixinPayPlugin') {
          return this.$u.toast('请通过微信直接打开链接再支付')
        }
        // #endif

        API_Deposit.createRechargeOrder(this.rechargeNumber).then(response => {
          const params = {
            payment_plugin_id: this.payment_plugin_id,
            pay_mode: 'normal',
            client_type: client_type,
            openid: this.openid
          }
          console.log(response)

          if (this.payment_plugin_id === 'fastPayMiniPlugin') {
            return this.openMini(response, '')
          }

          API_Deposit.paymentRechargeOrder(params, response.recharge_sn).then(result => {
            console.log(params, result)
            if (result && result.payment_method == '支付宝聚付') {
              setTimeout(() => {
                this.$u.route(`/mine-module/balance-detailed2`)
              }, 3000)
              // #ifdef H5
              window.location.href = result.gateway_url
              // #endif
              // #ifdef APP-PLUS
              plus.runtime.openURL(result.gateway_url)
              // #endif
              return
            }
            if (result && result.payment_method == '微信聚付') {
              setTimeout(() => {
                this.$u.route(`/mine-module/balance-detailed2`)
              }, 3000)
              // #ifdef H5
              //非微信内部，跳过获取openid
              if (!this.is_weixin()) {
                window.location.href = result.gateway_url
              }
              // #endif
              // #ifdef APP-PLUS
              plus.runtime.openURL(result.gateway_url)
              // #endif
              return
            }

            if (params.payment_plugin_id === 'weixinPayPlugin') {
              //微信内嵌H5，调用wechatH5Pay方法
              // #ifdef H5
              if (typeof WeixinJSBridge == "undefined") {
                Payment.mobileH5Pay(result, this.payCallback, this.payFail)
              } else {
                Payment.wechatH5Pay(result, this.payCallback, this.payFail)
              }
              // #endif

              //微信小程序，调用wechatMiniPay方法
              // #ifdef MP-WEIXIN
              Payment.wechatMiniPay(result, this.payCallback, this.payFail)
              // #endif

              //微信App
              // #ifdef APP-PLUS
              Payment.wechatAppPay(result, this.payCallback, this.payFail)
              // #endif
              // } else if (typeof result.gateway_url == 'string') {
              //   // } else if (payment_plugin_id === 'fastpayPlugin') {
              //   let obj = JSON.parse(result.gateway_url)
              //   console.log(obj)
              //   this.launchMini(obj)
            } else {
              // #ifdef H5
              //调起支付宝支付
              Payment.aliPayH5(result, this.payCallback, this.payFail)
              // #endif

              // #ifdef APP-PLUS
              Payment.aliPayApp(result, this.payCallback, this.payFail)
              // #endif
            }
          })
        })
      },
      //小程序 openid
      loadMiniOpenId() {
        if (this.openid == '') {
          API_Openid.fetchWeixinMiniOpenId().then(openid => {
            this.openid = openid
          }).catch(e => {
            this.$u.toast(`获取openid出现意外错误`)
          })
        }
      },
      //H5 openid
      loadH5OpenId(code) {
        //非微信内部，跳过获取openid
        if (!this.is_weixin()) {
          this.openid = "h5openid"
        }
        if (this.openid == '') {
          if (code == '') {
            API_Openid.createRedirectUri().then(url => {
              location.href = url
            })
          } else {
            API_Openid.fetchWeiXinH5OpenId(code).then(openid => {
              this.openid = openid
            })
          }
        }
      },
      payCallback() {
        this.rechargeNumber = ''
        this.showModal = true
        // uni.showModal({
        //   title: '支付提示',
        //   content: '请确认支付是否完成',
        //   confirmText: '支付成功',
        //   cancelText: '重新支付',
        //   success: () => {
        //     this.rechargeNumber = ''
        //   }
        // })
      },
      payFail(err) {
        console.log('fail:', err)
      },
      //获取支付方式
      getPaymentList() {
        // #ifdef APP-PLUS
        const client_type = 'NATIVE'
        // #endif

        // #ifdef H5
        const client_type = 'WAP'
        // #endif

        // #ifdef MP-WEIXIN
        const client_type = 'MINI'
        // #endif
        API_Trade.getPaymentList(client_type).then(response => {
          // 默认不选中支付方式
          response.forEach(item => {
            item.selected = false
          })
          this.paymentList = response
          console.log(this.paymentList)
          // 如果是在微信浏览器内则隐藏支付宝支付
          // #ifdef H5
          if (this.is_weixin()) {
            this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
          }
          // #endif
          // 如果是在小程序内则隐藏支付宝支付
          // #ifdef MP
          this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
          // #endif
        })
      },
      //自定义返回按钮
      handleClose() {
        console.log('自定义返回')
        // #ifdef H5
        const pages = getCurrentPages()
        if (pages.length > 1) {
          uni.navigateBack(1)
          return
        }
        //使用vue-router返回上一级
        let a = this.$router.go(-1)
        if (a == undefined) {
          //重新定向跳转页面
          uni.switchTab({
            url: '/pages/tabs/mine/mine'
          });
        }
        return
        // #endif
        uni.navigateBack(1)
      }
    }
  }
</script>

<style lang="scss">
  // page {
  //   background: #FFFFFF;
  // }

  .recharge-wrapper {
    margin: 20rpx;
    padding: 40rpx 20rpx 70rpx;
    background: #FFFFFF;
    border-radius: 20rpx;

    .title {
      color: #000;
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 30rpx;
    }

    .input {
      padding: 20rpx 30rpx;
      background-color: #F8F8F8;
      margin-top: 20rpx;

      .rmb {
        color: #FF1634;
        font-size: 50rpx;
        margin-right: 10rpx;
      }

      .placeholder {
        color: #666;
      }

      input {
        color: #000;
      }
    }
  }

  .upload_sfz {
    // width: 750rpx;
    height: 250rpx;
    background: $app-background;
    margin: 20rpx;
    border-radius: 20rpx;
  }

  .upload_content {
    height: 273rpx;
    display: flex;
    justify-content: space-around;
  }

  .upload_img {
    width: 330rpx;
    height: 209rpx;
    margin: 20rpx;
  }

  .upload_img image {
    width: 330rpx;
    height: 209rpx;
  }

  .upload_details {
    height: 70rpx;
    margin: 20rpx 0 0 20rpx;
    line-height: 70rpx;
    text-align: center;
    font-weight: bold;
    color: $app-Gold-color;
  }

  .upload_btn {
    margin-top: 50rpx;
  }

  .upload_btn button {
    width: 312rpx;
    height: 64rpx;
    line-height: 64rpx;
  }

  .payway-wrapper {
    margin-top: 80rpx;
    background: #FFFFFF;

    .payway-list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      border-bottom: 1rpx solid #E4E7ED;

      .wrapper {
        display: flex;
        align-items: center;

        view {
          image {
            width: 50rpx;
            height: 50rpx;
            border-radius: 50%;
            margin-right: 20rpx;
          }
        }
      }
    }
  }

  // .recharge_btn {
  //   width: 100%;
  //   height: 50px;
  //   line-height: 50px;
  //   font-size: 40rpx;
  //   background: $app-background;
  //   color: $app-Gold-color;
  //   text-align: center;
  //   position: fixed;
  //   bottom: 0;
  // }
  .recharge_btn {
    width: 90%;
    height: 110rpx;
    text-align: center;
    position: fixed;
    bottom: 100rpx;
    left: 5%;
    color: #fff;
    background: url(/static/images/chongzhi/button.png) no-repeat 0 0;
    background-size: cover;
  }
</style>